﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using PaintDotNet;
using PaintDotNet.Effects;

namespace LibFiltr
{
    public class KernelFilter
    {
        protected double[,] _kernel;
        protected int _radius;

        public KernelFilter(int radius)
        {
            _radius = radius;
            _kernel = new double[Size, Size];
        }

        public int Size
        {
            get { return 2 * _radius + 1; }
        }

        public void Filter(Surface dst, Surface src, Rectangle selection, Rectangle rect)
        {
            ColorBgra CurrentPixel;
            for (int y = rect.Top; y < rect.Bottom; y++)
            {
                for (int x = rect.Left; x < rect.Right; x++)
                {
                    CurrentPixel = src[x, y];
                    double sumR = 0, sumG = 0, sumB = 0;
                    for (int i = -_radius; i <= _radius; i++)
                    {
                        for (int j = -_radius; j <= _radius; j++)
                        {
                            // check for margins
                            int ipos = Math.Max(y + i, selection.Top), jpos = Math.Max(x + j, selection.Left);
                            ipos = Math.Min(ipos, selection.Bottom - 1); jpos = Math.Min(jpos, selection.Right - 1);
                            sumR += src[jpos, ipos].R * _kernel[i + _radius, j + _radius];
                            sumG += src[jpos, ipos].G * _kernel[i + _radius, j + _radius];
                            sumB += src[jpos, ipos].B * _kernel[i + _radius, j + _radius];
                        }
                    }
                    CurrentPixel.R = (byte)Math.Round(sumR);
                    CurrentPixel.G = (byte)Math.Round(sumG);
                    CurrentPixel.B = (byte)Math.Round(sumB);
                    dst[x, y] = CurrentPixel;
                }
            }
        }

        public void Print()
        {
            for (int i = 0; i < Size; i++)
            {
                Console.WriteLine();
                for (int j = 0; j < Size; j++)
                    Console.Write(_kernel[i, j]);
            }
        }
    }
}
